/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// d3d_main.cpp - 

#include "d3d_local.h"
#include <cuda.h>
#include <builtin_types.h>
#include <cuda_runtime_api.h>
#include <cuda_d3d9_interop.h>
#include "fluid_shared.h"


extern "C" 
{
	bool cuda_texture_2d(void* surface, size_t width, size_t height, size_t pitch, float t);
	void CUDA_FluidSimulate(void** surface, int width, int height, size_t pitch, float t, float dt, float vel_scale, float viscousity);
}

LPDIRECT3DTEXTURE9	tex[8];
static EVec4 buffer[SIZE_Y][SIZE_X];
static EVec4 *buffer_ptr = &buffer[0][0];


#define CUDA_CHECK(call)	\
	do {					\
		if (call!=cudaSuccess) { LOGF("^4CUDA Failed : %s\r\n^7", #call); }			\
		else { /*LOGF("^2CUDA Call : %s\r\n^7", #call);*/ }							\
	} while (0);



void CopyDataToDevice(LPDIRECT3DTEXTURE9 dst_tex, EVec4 *src) 
{
	CUDA_CHECK( cudaThreadSynchronize() );
	void* data;
	size_t size;
    CUDA_CHECK( cudaD3D9MapResources (1, (IDirect3DResource9 **)&dst_tex) );
	CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&data, dst_tex, 0, 0) );
	CUDA_CHECK( cudaD3D9ResourceGetMappedSize(&size,    dst_tex, 0, 0) );
	
	CUDA_CHECK( cudaMemcpy(data, src, SIZE_X * SIZE_Y * sizeof(EVec4), cudaMemcpyHostToDevice) );
	
    CUDA_CHECK( cudaD3D9UnmapResources (1, (IDirect3DResource9 **)&dst_tex) );
	CUDA_CHECK( cudaThreadSynchronize() );
}


void CopyTextureToTexture(LPDIRECT3DTEXTURE9 dst_tex, LPDIRECT3DTEXTURE9 src_tex) 
{
	CUDA_CHECK( cudaThreadSynchronize() );
	void* dst_data;
	void* src_data;
	size_t size1;
	size_t size2;
	
    CUDA_CHECK( cudaD3D9MapResources (1, (IDirect3DResource9 **)&dst_tex) );
    CUDA_CHECK( cudaD3D9MapResources (1, (IDirect3DResource9 **)&src_tex) );
	CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&dst_data, dst_tex, 0, 0) );
	CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&src_data, src_tex, 0, 0) );
	CUDA_CHECK( cudaD3D9ResourceGetMappedSize(&size1,    dst_tex, 0, 0) );
	CUDA_CHECK( cudaD3D9ResourceGetMappedSize(&size2,    dst_tex, 0, 0) );
	ASSERT(size1==size2);
	
	CUDA_CHECK( cudaMemcpy(dst_data, src_data, size1, cudaMemcpyDeviceToDevice) );
	
    CUDA_CHECK( cudaD3D9UnmapResources (1, (IDirect3DResource9 **)&dst_tex) );
    CUDA_CHECK( cudaD3D9UnmapResources (1, (IDirect3DResource9 **)&src_tex) );
	CUDA_CHECK( cudaThreadSynchronize() );
}

IVar	*cuda_fluid_viscosity;
IVar	*cuda_fluid_init_speed;

//
//	ECudaTest::ECudaTest
//
ECudaTest::ECudaTest(ED3DRenderSystem *rs)
{
	LOG_SPLIT("CUDA initialization");
	
	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;

	//	Init CUDA stuff :
	CUDA_CHECK( cudaD3D9SetDirect3DDevice(d3ddev) );
	CUDA_CHECK( cudaThreadSynchronize() );
	
	shell->AddCommand("cuda.TestBlot",		(EShellCmd_f)TestBlot_f, this);
	shell->AddCommand("cuda.TestStream",	(EShellCmd_f)TestStream_f, this);
	shell->AddCommand("cuda.TestStream2",	(EShellCmd_f)TestStream2_f, this);
	shell->AddCommand("cuda.TestMushroom",	(EShellCmd_f)TestMushroom_f, this);
	
	cuda_fluid_init_speed	=	shell->RegisterVar("cuda.fluid_init_speed", "800", 0);
	cuda_fluid_viscosity	=	shell->RegisterVar("cuda.fluid_viscosity",  "0.001", 0);

	//	Create textures :	
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );
		}
	}

	for (uint i=0; i<8; i++) {
		HRCALL( d3ddev->CreateTexture(SIZE_X, SIZE_Y, 1, 0, D3DFMT_A32B32G32R32F, D3DPOOL_DEFAULT, &tex[i], NULL) );

		CUDA_CHECK( cudaD3D9RegisterResource(tex[i], cudaD3D9RegisterFlagsNone) );
		
		CopyDataToDevice(tex[i], buffer_ptr);
	}

	/*TestStream();	
	TestBlot();
	TestMushroom();*/

	LOG_SPLIT("");
}


void ECudaTest::TestStream_f(ECudaTest *self, int argc, char **argv)
{
	self->TestStream();
}


void ECudaTest::TestStream2_f(ECudaTest *self, int argc, char **argv)
{
	self->TestStream2();
}


void ECudaTest::TestBlot_f(ECudaTest *self, int argc, char **argv)
{
	self->TestBlot();
}


void ECudaTest::TestMushroom_f(ECudaTest *self, int argc, char **argv)
{
	self->TestMushroom();
}


//
//	ECudaTest::TestStream
//
void ECudaTest::TestStream(void)
{
	//	Create textures :	
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );
		}
	}
	for (uint i=0; i<8; i++) {
		CopyDataToDevice(tex[i], buffer_ptr);
	}

	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			uint xx = (x>>5)&1;
			uint yy = (y>>5)&1;
			uint clr= (xx+yy)&1;
			buffer[y][x] = EVec4(clr, clr, clr, 1);
			buffer[y][x] = EVec4(0, 0, 0, 0);

			//buffer[y][x] = EVec4(0, FRand(), 0, 1);

			float dx = (float)x - SIZE_X/2;			
			float dy = (float)y - SIZE_Y/2;			
			float r = 20;
			
			//if (abs(dy)<r && dx<0) {
			if (abs(dy)<r && abs(dx)<50) {
				buffer[y][x] = EVec4(1, 1, 1, 0);
			}
		}
	}
	CopyDataToDevice(tex[FLUID_COLOR], buffer_ptr);
	
	//	VELOCITY :
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );

			float dx = (float)x - SIZE_X/2;			
			float dy = (float)y - SIZE_Y/2;			
			float r = 20;
			
			if (abs(dy)<r && abs(dx)<50) {
				buffer[y][x] = EVec4(800, 0, 0,0);
			}
			
			/*if (dx==3 && dy==1) {
				buffer[y][x] = EVec4(790, 0, 0,0);
			}  */
		}
	}
	CopyDataToDevice(tex[FLUID_VELOCITY], buffer_ptr);
}


//
//	ECudaTest::TestStream
//
void ECudaTest::TestStream2(void)
{
	//	Create textures :	
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );
		}
	}
	for (uint i=0; i<8; i++) {
		CopyDataToDevice(tex[i], buffer_ptr);
	}

	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			float dx = (float)x - SIZE_X/2;			
			float dy1 = (float)y - SIZE_Y/2 + 20;			
			float dy2 = (float)y - SIZE_Y/2 - 20;			
			float r = 40;

			float c = FRand(0.0, 0.9);
			c*=c;
			c*=c;
			c*=c;
			buffer[y][x] = EVec4(c,c,c,1);
			
			if (abs(dy1)<r && dx<-30) {
				buffer[y][x] = EVec4(1.0, 0.5, 0.5, 0);
			}
			
			if (abs(dy2)<r && dx>30) {
				buffer[y][x] = EVec4(0.5, 0.5, 1.0, 0);
			}
			
		}
	}
	CopyDataToDevice(tex[FLUID_COLOR], buffer_ptr);
	
	//	VELOCITY :
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );

			float dx = (float)x - SIZE_X/2;			
			float dy1 = (float)y - SIZE_Y/2 + 20;			
			float dy2 = (float)y - SIZE_Y/2 - 20;			
			float r = 40;
			
			if (abs(dy1)<r && dx<-30) {
				buffer[y][x] = EVec4(800, 0, 0,0);
			}
			
			if (abs(dy2)<r && dx>30) {
				buffer[y][x] = EVec4(-800, 0, 0,0);
			}
			
		}
	}
	CopyDataToDevice(tex[FLUID_VELOCITY], buffer_ptr);
}

//
//	ECudaTest::TestBlot
//
void ECudaTest::TestBlot(void)
{
	//	Create textures :	
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );
		}
	}
	for (uint i=0; i<8; i++) {
		CopyDataToDevice(tex[i], buffer_ptr);
	}

	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			uint xx = (x>>5)&1;
			uint yy = (y>>5)&1;
			uint clr= (xx+yy)&1;
			buffer[y][x] = EVec4(clr, clr, clr, 1);
			buffer[y][x] = EVec4(1, 1, 1, 1);

			//buffer[y][x] = EVec4(0, FRand(), 0, 1);

			float dx = (float)x - SIZE_X/2;			
			float dy = (float)y - SIZE_Y/2;			
			float r = 30;
			
			if (dy*dy + dx*dx < r*r) {
				buffer[y][x] = EVec4(0, 0, 0.4 + 0.5*clr, 0);
			}
		}
	}
	CopyDataToDevice(tex[FLUID_COLOR], buffer_ptr);
	
	//	VELOCITY :
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );

			float dx = (float)x - SIZE_X/2;			
			float dy = (float)y - SIZE_Y/2;			
			float r = 30;
			EVec4 vl(dx, dy, 0, 0);
			vl = Vec4Normalize(vl) * 800;
			vl.x = vl.x * 400 + FRand(-400,400);
			vl.y = vl.y * 400 + FRand(-400,400);
			
			if (dx*dx + dy*dy < r*r) {
				buffer[y][x] = EVec4(vl.x, vl.y, 0, 0);
			}
		}
	}
	CopyDataToDevice(tex[FLUID_VELOCITY], buffer_ptr);
}


//
//	ECudaTest::TestBlot
//
void ECudaTest::TestMushroom(void)
{
	//	Create textures :	
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );
		}
	}
	for (uint i=0; i<8; i++) {
		CopyDataToDevice(tex[i], buffer_ptr);
	}

	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			uint xx = (x>>5)&1;
			uint yy = (y>>5)&1;
			uint clr= (xx+yy)&1;
			buffer[y][x] = EVec4(clr, clr, clr, 1);
			buffer[y][x] = EVec4(1, 1, 1, 1);

			//buffer[y][x] = EVec4(0, FRand(), 0, 1);

			float dx = (float)x - SIZE_X/2;			
			float dy = (float)y - SIZE_Y/12;			
			float r = 30;
			
			if (dy*dy + dx*dx < r*r) {
				float g = FRand(0, 0.1);
				buffer[y][x] = EVec4(g, g, g, 0);
			}
		}
	}
	CopyDataToDevice(tex[FLUID_COLOR], buffer_ptr);
	
	//	VELOCITY :
	for (uint x=0; x<SIZE_X; x++) {
		for (uint y=0; y<SIZE_Y; y++) {
			buffer[y][x] = EVec4( 0,0,0,0 );

			float dx = (float)x - SIZE_X/2;			
			float dy = (float)y - SIZE_Y/12;			
			float r = 30;
			
			if (dx*dx + dy*dy < r*r) {
				buffer[y][x] = EVec4(0, 400, 0, 0);
			}
		}
	}
	CopyDataToDevice(tex[FLUID_VELOCITY], buffer_ptr);
}


//
//	ECudaTest::~ECudaTest
//
ECudaTest::~ECudaTest(void)
{
	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;
	LOG_SPLIT("CUDA shutting down");

	//	Remove textures :	
	for (uint i=0; i<8; i++) {
		CUDA_CHECK( cudaD3D9UnregisterResource(tex[i]) );
		CUDA_CHECK( cudaThreadSynchronize() );

		SAFE_RELEASE(tex[i]);
	}

	//	Shutdown CUDA :	
    CUDA_CHECK( cudaThreadExit() );
	CUDA_CHECK( cudaThreadSynchronize() );

	
	LOG_SPLIT("");
}


void ECudaTest::DyeSource(void)
{
}

//
//	ECudaTest::Run
//
void ECudaTest::Run(void)
{
	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;
	static float t = 0;
	const float dt = 0.01;
	t = t + dt;
	
	uint w, h;
	rs->GetScreenSize(w, h);
	rs->Set2DViewMode();

	HRCALL( d3ddev->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
	HRCALL( d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE) );
	HRCALL( d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
	HRCALL( d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );

	    CUDA_CHECK( cudaD3D9MapResources(8, (IDirect3DResource9**)tex) );
		CUDA_CHECK( cudaThreadSynchronize() );

		void* pData[8];
		size_t pitch;
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[0], tex[0], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[1], tex[1], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[2], tex[2], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[3], tex[3], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[4], tex[4], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[5], tex[5], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[6], tex[6], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&pData[7], tex[7], 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPitch(&pitch, NULL, tex[0], 0, 0) );
		
		CUDA_FluidSimulate(pData, SIZE_X, SIZE_Y, pitch, t, dt, 0.01, cuda_fluid_viscosity->Float());

	    CUDA_CHECK( cudaD3D9UnmapResources(8, (IDirect3DResource9**)tex) );
		CUDA_CHECK( cudaThreadSynchronize() );
	
		//CopyTextureToTexture(tex[0], tex[1]);
			

	float fw = w/2;
	float fh = h/2;
	HRCALL( d3ddev->SetTexture(0, tex[FLUID_COLOR]) );
	rs->DrawQuad( 0*fw, 0*fh,  1*fw, 1*fh, 0, 1, 1, 0, 0xFFFFFFFF);	

	HRCALL( d3ddev->SetTexture(0, tex[FLUID_VELOCITY_VIS]) );
	rs->DrawQuad( 1*fw, 0*fh,  2*fw, 1*fh, 0, 1, 1, 0, 0xFFFFFFFF);	

	HRCALL( d3ddev->SetTexture(0, tex[FLUID_PRESSURE]) );		 
	rs->DrawQuad( 0*fw, 1*fh,  1*fw, 2*fh, 0, 1, 1, 0, 0xFFFFFFFF);	

	HRCALL( d3ddev->SetTexture(0, tex[FLUID_PRESSURE_VIS]) );		 
	rs->DrawQuad( 1*fw, 1*fh,  2*fw, 2*fh, 0, 1, 1, 0, 0xFFFFFFFF);	


	/*HRCALL( d3ddev->SetTexture(0, tex[3]) );
	rs->DrawQuad( 1.0*fw, 1.0*fh,  1.5*fw, 1.5*fh, 0, 1, 1, 0, 0xFFFFFFFF);	

	HRCALL( d3ddev->SetTexture(0, tex[4]) );
	rs->DrawQuad( 1.5*fw, 1.0*fh,  2.0*fw, 1.5*fh, 0, 1, 1, 0, 0xFFFFFFFF);	

	HRCALL( d3ddev->SetTexture(0, tex[5]) );
	rs->DrawQuad( 1.0*fw, 1.5*fh,  1.5*fw, 2.0*fh, 0, 1, 1, 0, 0xFFFFFFFF);	

	HRCALL( d3ddev->SetTexture(0, tex[6]) );
	rs->DrawQuad( 1.5*fw, 1.5*fh,  2.0*fw, 2.0*fh, 0, 1, 1, 0, 0xFFFFFFFF);	*/
}












